'use strict';
var config=require('../utils/config');
var log4js = require('log4js');
var pool = require('../models/pool.js');
var async = require('async');

var stat = exports = module.exports = {};

var adKind = config.adKind;

log4js.configure({
  appenders: [ 
    {
      type: 'dateFile', //
      filename: config.log_path, 
      pattern: config.log_name+'-yyyy-MM-dd.log',
      alwaysIncludePattern: true,
      category: 'normal' 
    }
  ]
});
var logger = log4js.getLogger('normal');

		var dayStat = {};
		var planStat = {};
		var placeStat = {};
		var dspStat = {};
		
stat.save = function(req,type){
	
	var visit={};

	if(!req.query.planId  || !req.query.pid || !req.query.os)
		return 'error';
	var pid = req.query.pid;
if(pid!='INTER' && (pid.indexOf('.') < 0 || pid.indexOf('(') >=0 || pid.indexOf(' ') >=0|| pid.indexOf('(') >=0|| pid.indexOf('UNION') >=0|| pid.indexOf('AND') >=0)) return 'ok';
	
	var kinCode = req.query.type;
	if(!adKindCheck(kinCode)) return 'ok';
	
	
	visit.pid = req.query.pid;	
	visit.ip = req.query.ip;
	
	visit.planId = req.query.planId;
	
	visit.brand = req.query.brand;
	visit.cid = req.query.cid;
	visit.androidid = req.query.androidid;
	visit.os = req.query.os;
	visit.osv = req.query.osv;
	visit.car = req.query.car;
	visit.net = req.query.net;
	visit.area = req.query.area;
	visit.imei = req.query.androidimei;
	
	
	
	if(req.query.source)
		visit.source = req.query.source;
	else 
		visit.source = 1;
		
	if(visit.source == 0){
		visit.ua = req.headers['user-agent'];
	}

		
	var myDate = new Date();
	var year = myDate.getFullYear();
	var month = myDate.getFullYear()+'-'+ numFormate(myDate.getMonth()+1);
	var date = myDate.getFullYear()+'-'+ numFormate(myDate.getMonth()+1)+'-'+numFormate(myDate.getDate())
	visit.show_time = date +' ' + myDate.getHours()+':'+myDate.getMinutes() + ':'+myDate.getSeconds();
	
	
	visit.type = type;
	
	
	
	if(isNaN(visit.planId)){

			if(!global.dspStrategy.statCodes[visit.planId]) return "ok";
  		visitStat(visit.planId,visit,dspStat,date)
    	visitStat(visit.planId,visit,dspStat,month)
    	visitStat(visit.planId,visit,dspStat,year)   	
      	
    }else{

      	visitStat(visit.planId,visit,planStat,'total') 	
      	visitStat(visit.planId,visit,planStat,date)
      	
    }
    visitStat(visit.pid,visit,placeStat,year)
    visitStat(visit.pid,visit,placeStat,month) 
    visitStat(visit.pid,visit,placeStat,date) 
    
    visitStat(kinCode,visit,dayStat,date)
  	visitStat(kinCode,visit,dayStat,month)
  	visitStat(kinCode,visit,dayStat,year)
    
    	
  	if(visit.source == 0){
			logger.info(JSON.stringify(visit));
		}

	
	return 'ok';
}

function adKindCheck(kind){
	if(!adKind) return false;
	for(var i=0;i< adKind.length;i++){
		if(adKind[i] == kind) return true;
		
	}
	return false;
}


stat.persist = function(){
	
			var daySql = 'insert into TotalStat(type,day,shows,opShows,totalShows,clicks,opClicks,totalClicks,iosShows,iosClicks,cmccShows,cuccShows,ctccShows,cmccClicks,cuccClicks,ctccClicks) values ';
      var planSql = 'insert into AdItemStat( palnId,day,shows,opShows,totalShows,clicks,opClicks,totalClicks,iosShows,iosClicks,cmccShows,cuccShows,ctccShows,cmccClicks,cuccClicks,ctccClicks) values ';
      var placeSql = 'insert into AdSpaceStat( placeCode,day,shows,opShows,totalShows,clicks,opClicks,totalClicks,iosShows,iosClicks,cmccShows,cuccShows,ctccShows,cmccClicks,cuccClicks,ctccClicks) values ';
			var dspSql = 'insert into DspStat( dspCode,day,shows,opShows,totalShows,clicks,opClicks,totalClicks,iosShows,iosClicks,cmccShows,cuccShows,ctccShows,cmccClicks,cuccClicks,ctccClicks) values ';
			
			
			
			var tasks=[];
			
			insertOrUpdate(dayStat,daySql,tasks);		
			insertOrUpdate(placeStat,placeSql,tasks);
			insertOrUpdate(planStat,planSql,tasks);
			insertOrUpdate(dspStat,dspSql,tasks);

			
			for(var key in planStat){
				if(key.indexOf('total') >=0) continue;

				var theSql = "update AdItem set clientShows=clientShows+"+planStat[key].totalShows+", clientClicks=clientClicks+"+planStat[key].totalClicks+", baseShows=baseShows+"+planStat[key].shows+", baseClicks=baseClicks+"+planStat[key].clicks
											
											+" where id="+planStat[key].item;
								
				tasks.push(theSql);													
				
			}
			pool.acquire(function(err, connection) {
					async.eachSeries(tasks, function (theSql, callback) {	
									
					    connection.query(theSql, function(err) {
							    if (err) console.log(err);	
							    callback(null);				    						    
							});
					
					}, function (err) {
					    if (err) console.log(err);
					    pool.release(connection);
					});
			
			})
	
			dayStat={}
			planStat={}
			placeStat={}
			dspStat={}
	
}



function excute(theSql){
	pool.acquire(function(err, connection) {
		      		connection.query(theSql, function(err) {
							    if (err) console.log(err);					    
							    pool.release(connection);
							});
		      	
		      })
}

function numFormate(num){
	return num >9?num:('0'+num);
}

var statkeys = ['shows','opShows','totalShows','clicks','opClicks','totalClicks','iosShows','iosClicks','cmccShows','cuccShows','ctccShows','cmccClicks','cuccClicks','ctccClicks'];

function insertOrUpdate(stat,sql,tasks){
			for(var key in stat){

     		var theSql = sql + "('"+stat[key].item+"','"+stat[key].param + "'";
     		
     		for(var i=0;i<statkeys.length;i++){
		 			theSql += ","+stat[key][statkeys[i]];
		 		}
		 		theSql += ") ON DUPLICATE KEY UPDATE  "	
		 		for(var i=0;i<statkeys.length;i++){
		 			theSql += statkeys[i] +'='+statkeys[i]+stat[key][statkeys[i]] +",";
		 		}	
		 		
		 		theSql = theSql.substr(0,theSql.length -1);
     		tasks.push(theSql);		
		      	
		      
      }
}



function visitStat(key,visit,stat,param){
	
	 if(!stat[key+param]){ 
	 		var map = {'item':key,'param':param}
	 		for(var i=0;i<statkeys.length;i++){
	 			map[statkeys[i]]=0;
	 		}
	 		stat[key+param]=map;
	 			
	 	}
	 var ele = stat[key+param];
	 if(visit.type == 'click'){
	 		ele.totalClicks += 1;
	 		if(visit.source == '0') {
	 			ele.clicks += 1;
	 			if(visit.os == 'ios') ele.iosClicks += 1;
	 			
	 			if(visit.car == 'CMCC') ele.cmccClicks += 1;
	 			else if(visit.car == 'CUCC') ele.cuccClicks += 1;
	 			else if(visit.car == 'CTCC') ele.ctccClicks += 1;
	 		}
	 		else ele.opClicks += 1;
	 	
		}else if(visit.type == 'show'){
	 		ele.totalShows += 1;
	 		if(visit.source == '0') {
	 			ele.shows += 1;
	 			if(visit.os == 'ios') ele.iosShows += 1;
	 			if(visit.car == 'CMCC') ele.cmccShows += 1;
	 			else if(visit.car == 'CUCC') ele.cuccShows += 1;
	 			else if(visit.car == 'CTCC') ele.ctccShows += 1;
	 		}
	 		else ele.opShows += 1;
	 			
	 	
		}
		
}
  
